//定义全局变量
var xmlConfig;// 定义配置文件
var dialogType;// 对话框类型：增加，删除，修改

// 集中定义jQuery选择器
var grid = $('#maingrid'); // 生成表格
var searchFiled = $("#search-field");// 生成搜索字段
var serchButton = $('#search-button'); // 生成搜索按钮
var mainTool = $('#maintool'); // 生成工具栏
var dialogAdd = $("#dialog-Add"); // 生成添加对话框
var addForm = $('#addForm'); // 生成添加表单
var dialogMatReq = $("#dialog-MatReq"); // 生成添加对话框
var reqSendTime = $("#reqSendTime");// 生成发运时间

// 设置表格操作提交的网址
var searchUrl = path + "sm/filterQuery.html";
var addUrl = path + "sm/gridAdd.html";
var deleteUrl = path + "sm/gridDelete.html";
var editUrl = path + "sm/gridEdit.html";
var matReqUrl = path + "sm/rm/MatReqCtl/matReq.html";

$(document).ready(function() {
	loadXml(); // 加载配置
	loadLayout();// 加载布局
	loadGrid();// 加载表格
	loadSearchPanel();// 加载搜索面板
	loadButtonBar();// 加载工具栏
	loadDialogAdd();// 加载对话框-增加
	loadDialogMatReq();// 加载对话框-要料申请
	search();// 搜索
});

// 加载XML配置文件
function loadXml() {
	$.ajax({
		url : xmlPath,// xmlPath在JSP中定义
		async : false,
		type : "GET",
		dataType : "xml",
		timeout : 1000,
		cache : false, // 禁用缓存
		error : function(xml) {
			$.omMessageBox.alert({
				type : 'error',
				title : '失败',
				content : '加载XML文档出错，请检查路径：<br>' + xmlPath
			});
		},
		success : function(xml) {
			xmlConfig = $.xml2json(xml);
		}
	});
};

// 加载布局
function loadLayout() {
	$('#page').omBorderLayout({
		panels : [ {
			id : "north-panel",
			title : "搜索",
			region : "north",
			height : 125,
			resizable : true,
			collapsible : true
		}, {
			id : "center-panel",
			header : false,
			region : "center"
		} ]
	});
}

// 加载表格
function loadGrid() {
	grid.omGrid(xmlConfig.grid);
};

// 加载搜索面板
function loadSearchPanel() {
	// 插入搜索表单
	searchFiled.tbForm(xmlConfig.search);
	// 加载搜索按钮
	serchButton.omButton({
		icons : {
			left : path + 'resources/sm/images/search.png'
		},
		width : 70,
		onClick : function(event) {
			if ($("#uploadStatus", searchFiled).val() == "Y") {
				mainTool.hide();
			} else {
				mainTool.show();
			}
			search();
		}
	});
}

function search() {
	// var rules = [ {
	// "field" : "uploadStatus",
	// "op" : "equal",
	// "value" : "N",
	// "type" : "string"
	// }, {
	// "field" : "timeStamp",
	// "op" : "greater",
	// "value" : "today",
	// "type" : "date"
	// } ];
	//
	// var group = {
	// "op" : "and",
	// "rules" : rules
	// };
	var extraData = xmlConfig.grid.extraData;
	var group = $.bulidFilterGroup(searchFiled);
	extraData.where = JSON.stringify(group);
	if (window.console)
		console.log(extraData.where);
	grid.omGrid({
		dataSource : searchUrl,
		extraData : extraData
	}, 'reload');

}

// 加载工具栏
function loadButtonBar() {
	var buttons = [ {
		label : "增加",
		id : "grid-add",
		onClick : function() {
			addForm.clearForm();
			var selections = grid.omGrid('getSelections', true);
			var selection = null;
			if (selections.length == 1) {
				selection = selections[0];
			}
			dialogType = 'add';
			showDialogAdd('新增记录', selection);
		}
	}, {
		separtor : true
	}, {
		label : "删除",
		id : "grid-delete",
		onClick : function() {
			var selections = grid.omGrid('getSelections', true);
			if (selections.length != 1) {
				$.omMessageBox.alert({
					content : '请选择一行记录',
				});
			} else {
				dialogType = 'delete';
				showDialogAdd('删除记录', selections[0]);
			}
		}
	}, {
		separtor : true
	}, {
		label : "修改",
		id : "grid-edit",
		onClick : function() {
			var selections = grid.omGrid('getSelections', true);
			if (selections.length != 1) {
				$.omMessageBox.alert({
					content : '请选择一行记录',
				});
			} else {
				dialogType = 'edit';
				showDialogAdd('修改记录', selections[0]);
			}
		}
	}, {
		separtor : true
	}, {
		label : "发送要料申请",
		id : "mat-Req",
		onClick : function() {
			var selections = grid.omGrid('getSelections', true);
			if (selections.length > 0) {
				showDialogMatReq('发送要料申请');
			} else {
				$.omMessageBox.alert({
					content : '请至少选择一行记录',
				});
			}
		}
	} ];
	var btnBarCfg = {
		btns : buttons
	};
	mainTool.omButtonbar(btnBarCfg);
}

// 加载新增对话框
function loadDialogAdd() {
	loadAddForm();
	var buttons = [ {
		text : '确定',
		click : function() {
			switch (dialogType) {
			case 'add':
				gridAdd();
				break;
			case 'delete':
				gridDelete();
				break;
			case 'edit':
				gridEdit();
				break;
			default:
				break;
			}
		}
	}, {
		text : '取消',
		click : function() {
			dialogAdd.omDialog("close");
		}
	} ];
	dialogAdd.omDialog({
		width : xmlConfig.add.dialogWidth,
		height : xmlConfig.add.dialogHeight,
		autoOpen : false,
		resizable : false,
		modal : true,
		buttons : buttons
	});
	// 显示dialog并初始化里面的输入框的数据
	showDialogAdd = function(title, rowData) {
		if (rowData != null) {
			addData2Form(rowData, addForm);
			addData2FormAfter(rowData, addForm);
		}
		dialogAdd.omDialog("option", "title", title);
		dialogAdd.omDialog("open");// 显示dialog
	};
}

// 加载窗体
function loadAddForm() {
	addForm.tbForm(xmlConfig.add);
}

// 添加一条记录
function gridAdd() {
	if (!(addForm.validate().form())) {
		return false;
	}
	var infoArray = addForm.formToArray();
	var infoJson = {};
	for ( var i = 0; i < infoArray.length; i++) {
		if (infoArray[i].value != "") {
			infoJson[infoArray[i].name] = infoArray[i].value;
		} else {
			infoJson[infoArray[i].name] = null;
		}
	}
	delete infoJson["materialDesc"];
	var info = "selectedRow=" + JSON.stringify(infoJson);
	info = info + "&className=" + xmlConfig.grid.extraData.package + "."
			+ xmlConfig.grid.extraData.view;
	var desc="要料申请";
	info = info + "&addEntityMgr=" + xmlConfig.addEntityMgr;
	info = info + "&desc=" + desc;
	if (window.console)
		console.log(info);
	$.ajax({
		type : "POST",
		async : false,
		url : addUrl,
		data : info,
		dataType : "json",
		success : function(data) {
			if (data.success) {
				$.omMessageBox.alert({
					type : 'success',
					title : '成功',
					content : data.message
				});
				dialogAdd.omDialog("close");// 关闭收货对话框
				grid.omGrid('reload');// 刷新表格数据
				addForm.clearForm();
			} else {
				$.omMessageBox.alert({
					type : 'error',
					title : '失败',
					content : data.message
				});

			}

		},
		error : function() {
			$.omMessageBox.alert({
				type : 'error',
				title : '失败',
				content : 'Ajax提交不成功或未得到有效返回'
			});
		}
	});
}

function gridDelete() {
	var selections = grid.omGrid('getSelections', true);
	var infoJson = selections[0];
	delete infoJson["materialDesc"];
	var clsName = xmlConfig.grid.extraData.package + "."
			+ xmlConfig.grid.extraData.view;
	var info = {
		"selectedRow" : JSON.stringify(infoJson),
		"className" : clsName
	};
	
	$.ajax({
		type : "POST",
		url : deleteUrl,
		data : info,
		dataType : "json",
		success : function(data) {
			if (data.success) {
				$.omMessageBox.alert({
					type : 'success',
					title : '成功',
					content : data.message
				});
				dialogAdd.omDialog("close");// 关闭收货对话框
				grid.omGrid('reload');// 刷新表格数据
			} else {
				$.omMessageBox.alert({
					type : 'error',
					title : '失败',
					content : data.message
				});

			}

		},
		error : function() {
			$.omMessageBox.alert({
				type : 'error',
				title : '失败',
				content : 'Ajax提交不成功或未得到有效返回'
			});
		}
	});
}

function gridEdit() {
	if (!(addForm.validate().form())) {
		return false;
	}
	var selections = grid.omGrid('getSelections', true);
	var infoJson = selections[0];
	var infoArray = addForm.formToArray();
	for ( var i = 0; i < infoArray.length; i++) {
		if (infoArray[i].value != "") {
			infoJson[infoArray[i].name] = infoArray[i].value;
		} else {
			infoJson[infoArray[i].name] = null;
		}
	}
	var info = "selectedRow=" + JSON.stringify(infoJson);
	info = info + "&className=" + xmlConfig.grid.extraData.package + "."
			+ xmlConfig.grid.extraData.view;
	info = info + "&addEntityMgr=" + xmlConfig.addEntityMgr;
	if (window.console)
		console.log(info);
	$.ajax({
		type : "POST",
		url : editUrl,
		data : info,
		dataType : "json",
		success : function(data) {
			if (data.success) {
				$.omMessageBox.alert({
					type : 'success',
					title : '成功',
					content : data.message
				});
				dialogAdd.omDialog("close");// 关闭收货对话框
				grid.omGrid('reload');// 刷新表格数据
				addForm.clearForm();
			} else {
				$.omMessageBox.alert({
					type : 'error',
					title : '失败',
					content : data.message
				});
			}
		},
		error : function() {
			$.omMessageBox.alert({
				type : 'error',
				title : '失败',
				content : 'Ajax提交不成功或未得到有效返回'
			});
		}
	});
}

// 将表格的行数据赋值到窗体
function addData2FormAfter(rowData, form) {
	$(":input", form).each(function() {
		if (this.name == "sendFactory" && $(this).hasClass("field")) {
			var value = rowData[this.name];
			value = rowData["sendFactory"] + "-" + rowData["purcharseGroup"];
			$(this).omCombo('value', value);
		}
	});
}

// 加载新增对话框
function loadDialogMatReq() {
	reqSendTime.omCalendar({
		showTime : true
	});
	var buttons = [ {
		text : '确定',
		click : function() {
			var selections = grid.omGrid('getSelections', true);
			var sendTime = reqSendTime.val();
			if (sendTime != '' && dateCmp(sendTime)) {
				matReq(selections, sendTime);
			} else {
				$.omMessageBox.alert({
					type : 'error',
					title : '失败',
					content : '要求送料时间不能为空并且要大于当前系统时间'
				});
			}
		}
	}, {
		text : '取消',
		click : function() {
			dialogMatReq.omDialog("close");
		}
	} ];
	dialogMatReq.omDialog({
		width : 400,
		height : 100,
		autoOpen : false,
		resizable : false,
		modal : true,
		buttons : buttons
	});
	// 显示dialog并初始化里面的输入框的数据
	showDialogMatReq = function(title) {
		dialogMatReq.omDialog("option", "title", title);
		dialogMatReq.omDialog("open");// 显示dialog
	};
}

function matReq(selections, sendTime) {
	var info = {
		"reqSendTime" : sendTime,
		"selectedRows" : JSON.stringify(selections)
	};
	$.ajax({
		type : "POST",
		async : false,
		url : matReqUrl,
		data : info,
		dataType : "json",
		success : function(data) {
			if (data.success) {
				$.omMessageBox.alert({
					type : 'success',
					title : '成功',
					content : data.message
				});
				dialogMatReq.omDialog("close");// 关闭收货对话框
				grid.omGrid('reload');// 刷新表格数据
				reqSendTime.val('');
			} else {
				$.omMessageBox.alert({
					type : 'error',
					title : '失败',
					content : data.message
				});

			}

		},
		error : function() {
			$.omMessageBox.alert({
				type : 'error',
				title : '失败',
				content : 'Ajax提交不成功或未得到有效返回'
			});
		}
	});
}

function dateCmp(date_string) {
	var tm = $.omCalendar.parseDate(date_string, "yy-mm-dd H:i:s");
	var sysdate = new Date();
	var diff = tm.getTime() - sysdate.getTime();
	return diff > 0;
}